/**
 * <pre>
 * Copyright:		Copyright(C) 2011-2012, ketayao.com
 * Date:			2013年8月7日
 * Author:			<a href="mailto:ketayao@gmail.com">ketayao</a>
 * Version          1.0.0
 * Description:		
 *
 * </pre>
 **/
package com.ketayao.action.admin;

import java.io.File;
import java.io.IOException;
import java.util.List;

import com.ketayao.fensy.mvc.RequestContext;
import com.ketayao.fensy.mvc.UploadFile;
import com.ketayao.fensy.webutil.StorageService;

/** 
 * 	
 * @author 	<a href="mailto:ketayao@gmail.com">ketayao</a>
 * Version  1.0.0
 * @since   2013年8月7日 下午2:36:29 
 */
public class FileAction {
	private static final long MAX_IMG_SIZE = 1 * 1024 * 1024;

	public void upload(RequestContext rc) throws IOException {
		File imgFile = rc.getImage("imgFile");
		if (imgFile.length() > MAX_IMG_SIZE) {
			rc.printJson(new String[] { "error", "message" }, new Object[] {
					1, "File is too large" });
			return;
		}
		
		StorageService ss = StorageService.IMAGE;
		String path = ss.save(imgFile);
		String url = rc.getContextPath() + "/" + ss.getReadPath() + path;
		rc.printJson(new String[] { "error", "url" }, new Object[] {0, url});
	}
	
	public void uploads(RequestContext rc) throws IOException {
		List<UploadFile> list = rc.getFiles();
		if(list != null){
			for(UploadFile imgFile : list){
//				System.out.println("fileName:"+imgFile.getFile().getName() + ";fileName:" + imgFile.getFileName() + ";OriginalFileName:" +imgFile.getOriginalFileName() + ";ContentType:" + imgFile.getContentType());
				if (imgFile.getFile().length() > MAX_IMG_SIZE) {
					rc.printJson(new String[] { "error", "message" }, new Object[] {
							1, "File is too large" });
					return;
				}
				
				StorageService ss = StorageService.IMAGE;
				String path = ss.save(imgFile.getFile());
				String url = rc.getContextPath() + ss.getReadPath() + path;
				String originalFileName = imgFile.getFileName();
				rc.printJson(new String[] { "error", "url" ,"title"}, new Object[] {0, url,originalFileName.substring(0,originalFileName.lastIndexOf("."))});
			}
		}
	}
}
